/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 *
 * @author Dentinho
 */
public class DAOGenerico<T> {

    private EntityManager em;
    private Class<T> clazz;

    public EntityManager getEm() {
        return em;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    public DAOGenerico(EntityManager em, Class<T> clazz) {
        this.em = em;
        this.clazz = clazz;
    }

    public void salvar(T t) {
        this.em.getTransaction().begin();
        this.em.persist(t);
        this.em.getTransaction().commit();
    }

    public void atualizar(T t) {
        this.em.getTransaction().begin();
        this.em.merge(t);
        this.em.getTransaction().commit();
    }

    public void apagar(T t) {
        this.em.getTransaction().begin();
        this.em.remove(t);
        this.em.getTransaction().commit();
    }

    public T buscar(Long id, Class<T> clazz) {
        return em.find(clazz, id);
    }

    public List<T> buscarTodos(Class<T> clazz) {
        Query todos = em.createQuery("select o from " + clazz.getSimpleName() + " o");
        return todos.getResultList();
    }

    public List<T> buscarProduto(Class<T> clazz,String text) {
        Query produtos = em.createQuery("select o.id,o.descricao, o.preco,o.quantidade from " + clazz.getSimpleName() + " o where o.descricao like '%"+text+"%'");
        System.out.println("dao: "+produtos.getResultList().size());
        return produtos.getResultList();
    }
    
    public List<T> buscarNome(Class<T> clazz,String text) {
        Query clientes = em.createQuery("select o.nome, o.cpf from " + clazz.getSimpleName() + " o where o.nome like '%"+text+"%'");
        System.out.println("dao: "+clientes.getResultList().size());
        System.out.println("dao: "+clientes.getResultList());
        return  clientes.getResultList();
    }
    
    public Object buscarCpf(Class<T> clazz, String cpf){
        Query cliente = em.createQuery("select o from "+ clazz.getSimpleName()+" o where o.cpf ='"+cpf+"'");
        return cliente.getSingleResult();
    }

    public Object login(Class<T> clazz,String login, String senha) {
        Query logado = em.createQuery("select o from "+ clazz.getSimpleName()+" o where o.usuario ='"+login+"' and o.senha ='"+senha+"'");
        if(logado.getResultList().size()>0){
           return logado.getSingleResult();
        }else{
            return null;
        }
    }

}
